from bot.enterprise_wechat_gpt.util.constant_role_name import *
import pandas as pd
import os
abs_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)


# 把对话历史的数组转换成字符串
def transfer_conversation_list_to_str(conversation_history):
    return '\n###'.join([list(d.keys())[0] + ':' + list(d.values())[0] for d in conversation_history])


def clean_conversation_history(raw_conversation_history):
    # 清洗对话历史，去掉无用的消息
    conversation_history = filter_not_text(raw_conversation_history)
    # conversation_history = filter_transfer_before(conversation_history)
    conversation_history = merge_role_conversation(conversation_history)
    return conversation_history


def merge_role_conversation(raw_conversation_history, role1=ASSISTANT, role2=USER):
    # 整合同一角色的连续多行对话 为一行
    deal_conversation_history = list()
    for i in range(len(raw_conversation_history)):
        if i > 0 and role1 in raw_conversation_history[i] and role1 in raw_conversation_history[i - 1]:
            deal_conversation_history[-1][role1] = deal_conversation_history[-1][role1] + '，' + \
                                                   list(raw_conversation_history[i].values())[0]
        elif i > 0 and role2 in raw_conversation_history[i] and role2 in raw_conversation_history[i - 1]:
            deal_conversation_history[-1][role2] = deal_conversation_history[-1][role2] + '，' + \
                                                   list(raw_conversation_history[i].values())[0]
        else:
            deal_conversation_history.append(raw_conversation_history[i])
    return deal_conversation_history


def filter_transfer_before(raw_conversation_history):
    # 过滤掉历史对话里，转人节点及转人节点之前的消息，以免影响后续机器判断转人
    start_index = None

    for i, item in enumerate(raw_conversation_history):
        if '系统' in item:
            start_index = i

    if start_index is not None:
        return raw_conversation_history[start_index + 1:]
    else:
        return raw_conversation_history  # 如果没有找到'系统'，则返回原列表


def filter_not_text(raw_conversation_history):
    return [message for message in raw_conversation_history if message.get('msg_type', 'text') == 'text']


def parse_history(dialogue_text):
    # 解析测试用例
    lines = dialogue_text.strip().split('\n')
    remainder = 0
    if "用户：" in lines[0]:
        remainder = 1
        lines[0] = lines[0].replace("用户：", "")
    history = []
    for i, line in enumerate(lines):
        # 偶数行是助理，奇数行是用户
        key = ASSISTANT if i % 2 == remainder else USER
        history.append({key: line.strip()})
    print(history)
    return history


def load_test_data(path='{}/raw_data/日常case测试集.xlsx'.format(abs_path)):
    df = pd.read_excel(path)
    # print(df.columns)
    # ['客户ID', '业务类型', '测试对话记录', '标准话术', '记录时间', '对话真实时间', '是否使用']
    print('业务类型统计: ')
    print(pd.DataFrame(df['业务类型'].value_counts(sort=True)))
    res_coll = {}
    infos = df['测试对话记录'].tolist()
    for idx, dialogue_text in enumerate(infos):
        dialogue = parse_history(dialogue_text)
        # print(idx, dialogue)
        res_coll[idx] = dialogue
    return res_coll




if __name__ == '__main__':
    raw_conversation_history = [{'京东金融福利推荐官': '🍄50元支付券您应该不会拒绝吧？新用户申请京东联名信用卡通过直接到账！\n\n😋有用款需求别错过哦，免费办理，最高额度20W，以银行评估为准。\n\n🌏点击专属链接【 http://3.cn/-10brFunN】即可申请！具体权益以页面显示为准。 \x02\x01 ·', 'msg_type': 'text', 'msgtime': 1692791049},
                                {'用户': '怎样恢复额度？？？？？？', 'msg_type': 'text', 'msgtime': 1692791097},
                                {'京东金融福利推荐官': '您想要恢复金条的额度对吗~您的金条账户现在还可用吗~页面是怎么显示的呢', 'msg_type': 'image', 'msgtime': 1692791178},
                                {'用户': 'https://s3.jdpay.com/we-chat-media-oss/7114353749987718305_1692791245622_external.jpg?AWSAccessKeyId=LOCAL_JRSS_043B4B742AF3DC187422F&Expires=2008151248&Signature=XyxFmFpUVX8hN%2BL4wleYJ5L4o3E%3D', 'msg_type': 'image', 'msgtime': 1692791241},
                                {'用户': '这样', 'msg_type': 'text', 'msgtime': 1692791244},
                                {'用户': '原有的七千额度现在用不了，是不是因为还欠有千几块所以不能用', 'msg_type': 'weapp', 'msgtime': 1692791316}]
    text = filter_not_text(raw_conversation_history)
    print(text)
    text = filter_transfer_before(text)
    print(text)
    print(merge_role_conversation(text))

